import { StyleSheet, Pressable, FlatList } from "react-native";
import { MaterialIcons } from "@expo/vector-icons";
import { Text, View } from "../components/Themed";
import Header from "../components/Header";
import React from "react";
import { getBillList, getBillStatis } from "../api/home";
import button from "../styles/button";
import vars from "../styles/vars";
import SuperCard from "../components/SuperCard";
import { Text as CardText, List } from "react-native-paper";
import FabVoice from "../components/FabVoice";
import Layout from "../constants/Layout";
import createDayjs, { weekDay } from "../utils/datetime";
import SuperIcon from "../components/SuperIcon";
import SummaryDetails from "../components/SummaryDetails";
import { RootTabScreenProps } from "../types";

export default function TabOneScreen({ navigation }: RootTabScreenProps<"TabOne">) {
  const [data, setData] = React.useState<API.StatisData>({});
  const [list, setList] = React.useState<API.BillListSection[]>([]);
  React.useEffect(() => {
    getBillStatis().then((response) => setData(response));
  }, []);

  React.useEffect(() => {
    getBillList().then((response) => {
      setList(response);
    });
  }, []);
  console.log(createDayjs().format("M.D"));

  return (
    <View
      lightColor={vars["light-2"]}
      darkColor={vars["dark-2"]}
      style={{ height: Layout.window.height - 50 }}>
      <Header visiable={true} route={"home"} />
      <View style={styles.summary}>
        <SummaryDetails
          containerStyle={{ flex: 1 }}
          textStyle={{ color: vars["dark-2"], fontSize: 16, fontWeight: "500" }}
          title="本月收入"
          text={data?.richer}
        />
        <SummaryDetails
          containerStyle={{ flex: 1 }}
          textStyle={{ color: vars["dark-2"], fontSize: 16, fontWeight: "500" }}
          title="本月结余"
          text={data?.balance}
        />
        <SummaryDetails
          containerStyle={{ flex: 2 }}
          textStyle={{ color: vars["dark-3"], fontWeight: "200" }}
          title="剩余预算"
          text="点击设置"
          click={() => navigation.navigate("Modal")}
        />
      </View>
      <View style={styles.summary}>
        <SummaryDetails
          textStyle={{ color: vars["green-3"], fontSize: 24, fontWeight: "500" }}
          title="本月支出"
          text={data?.expend}
        />
      </View>
      <View style={{ margin: 20 }}>
        <Pressable style={button.container} onPress={() => console.log("pressable home")}>
          <MaterialIcons name={"note-add"} size={24} color={vars["light-2"]} />
          <Text style={[button.text, styles.text]}>添加一条新记账</Text>
        </Pressable>
      </View>
      {!list.length ? (
        <SuperCard url={""} title={"您还没有任何记账"}>
          <BlankText></BlankText>
        </SuperCard>
      ) : (
        <FlatList data={list} renderItem={({ item }) => <BillListSection {...item} />}>
          <Text style={{ textAlign: "center", color: vars["grey-3"] }}>没有更多数据</Text>
        </FlatList>
      )}
      <FabVoice />
    </View>
  );
}

function BillListSection(props: API.BillListSection) {
  const { datetime, income, expend, contents } = props;
  const today = createDayjs();
  const _datetime = createDayjs(datetime);
  const diff = today.diff(_datetime, "day");
  const week = weekDay(datetime);
  const title = diff === 0 ? `今天` : diff === 1 ? `昨天` : `${_datetime.format("M.D")}`;
  return (
    <List.Section>
      <List.Subheader style={styles["sub-header"]}>
        <View style={{ flex: 2, flexDirection: "row" }}>
          <Text style={styles.sectionDay}>{title} &nbsp;</Text>
          <Text style={styles.sectionWeek}>&nbsp;{week}</Text>
        </View>
        <View style={{ flex: 1, flexDirection: "row" }}>
          <Text style={{ color: vars["dark-1"], opacity: 0.8 }}>收入: &nbsp;</Text>
          <Text style={{ color: vars["green-1"] }}>&nbsp;{income}</Text>
        </View>
        <View style={{ flex: 1, flexDirection: "row" }}>
          <Text style={{ color: vars["dark-1"], opacity: 0.8 }}>支出: &nbsp;</Text>
          <Text style={{ color: "#cd5e3c" }}>&nbsp;{expend}</Text>
        </View>
      </List.Subheader>
      {contents?.map((it, index) => {
        return (
          <View key={index} style={styles.sectionItem}>
            <List.Item
              title={(props) => (
                <View style={{ display: "flex", flexDirection: "row" }}>
                  <Text
                    style={{
                      color: props.color,
                      backgroundColor: "#fff",
                      flex: 9,
                    }}>
                    {it.title}
                  </Text>
                  <Text
                    style={{
                      color: it.consumeType === "in" ? vars["green-1"] : "#cd5e3c",
                      backgroundColor: "#fff",
                      flex: 1,
                    }}>
                    {it.consumeType === "in" ? +it.money : -it.money}
                  </Text>
                </View>
              )}
              left={() => <SuperIcon style={styles.icon} name={it.type} size={24} />}
            />
          </View>
        );
      })}
    </List.Section>
  );
}

function BlankText() {
  return (
    <View lightColor={vars["light-2"]}>
      <SuperCard url={""} title={"您还没有任何记账"}>
        <CardText>
          想记点什么？试试点击或
          <CardText>长按</CardText>
          右下方按钮进行快速记账
        </CardText>
      </SuperCard>
    </View>
  );
}

const styles = StyleSheet.create({
  summary: {
    paddingTop: 10,
    paddingLeft: 20,
    paddingRight: 20,
    paddingBottom: 10,
    display: "flex",
    flexDirection: "row",
  },
  text: {
    marginLeft: 10,
  },
  "sub-header": {
    display: "flex",
  },
  sectionDay: {
    color: vars["dark-2"],
    fontWeight: "bold",
  },
  sectionWeek: {
    color: vars["dark-1"],
    opacity: 0.7,
  },
  subTitle: {},
  sectionItem: {
    marginLeft: 16,
    marginRight: 16,
    paddingLeft: 12,
    paddingRight: 12,
    backgroundColor: vars["light-1"],
  },
  titleStyle: {
    color: vars["dark-2"],
  },
  icon: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
  },
});
